// 在这个文件可以对axios进行一些初始化配置
import * as _ from 'lodash'
import system from '@/service/src/systemService'

let timer = null
let startTime = Date.now()
let serverDate = startTime
let loaded = false

system.now().then(res => {
  serverDate = new Date(res.data).getTime()
}).finally(() => {
  loaded = true
  utils.getNow = function () {
    return new Promise(resolve => {
      resolve(new Date(Date.now() - startTime + serverDate))
    })
  }
})

const utils = {
  getNow () {
    return new Promise(resolve => {
      if (loaded) {
        resolve(new Date(Date.now() - startTime + serverDate))
      } else {
        timer = setInterval(() => {
          if (loaded) {
            clearInterval(timer)
            resolve(new Date(Date.now() - startTime + serverDate))
          }
        }, 100)
      }
    })
  },
  parseDate (date) {
    if (_.isEmpty(date)) {
      return new Date()
    }
    if (!(date instanceof Date)) {
      date = new Date(date.replace(/-/g, '/'))
    }
    return date
  },
  getDayOfWeek (date) {
    if (!(date instanceof Date)) {
      date = new Date(date.replace(/-/g, '/'))
    }
    return '星期' + '日一二三四五六'.charAt(date.getDay())
  },
  getShortDate (date) {
    if (!(date instanceof Date)) {
      if (_.isEmpty(date)) {
        return '-'
      } else {
        date = new Date(date.replace(/-/g, '/'))
      }
    }
    return date.format('yyyy-MM-dd')
  },
  getFormatDate (date, format) {
    if (!(date instanceof Date)) {
      if (_.isEmpty(date)) {
        return '-'
      } else {
        date = new Date(date.replace(/-/g, '/'))
      }
    }
    return date.format(format)
  },
  /**
   * 计算小时数
   * @param beginTime 开始时间
   * @param endTime   结束时间
   * @param isSkipWeekend 是否跳过周末，默认跳过
   */
  getWorkTimeHours (beginTime, endTime, isSkipWeekend = true) {
    let total = 0
    let days = (utils.parseDate(endTime.format('yyyy/MM/dd')) - utils.parseDate(beginTime.format('yyyy/MM/dd'))) / 86400000
    total += days * 7.5
    let h1 = beginTime.getHours()
    let m1 = beginTime.getMinutes()
    let d1 = beginTime.getDay()
    h1 += m1 / 60
    if (h1 <= 12) {
      total += 12 - h1 + 4
    } else if (h1 > 13.5) {
      total += 17.5 - h1
    } else if (h1 > 17.5) {
      total += 0
    } else {
      total += 4
    }

    let h2 = endTime.getHours()
    let m2 = endTime.getMinutes()
    let d2 = endTime.getDay()
    h2 += m2 / 60
    if (h2 <= 12) {
      total += h2 - 8.5
    } else if (h2 > 13.5) {
      total += h2 - 13.5 + 3.5
    } else if (h2 > 17.5) {
      total += 7.5
    } else {
      total += 3.5
    }
    total -= 7.5
    if (isSkipWeekend) {
      // 判断有几个周末
      if (d1 > d2) {
        total -= 7.5 * 2
      }
      total -= _.floor(days / 7) * 7.5 * 2
    }
    return _.round(total, 2)
  }
}

function install (Clazz) {
  Clazz.prototype.$dateUtils = utils
}

export const parseDate = utils.parseDate

export default {
  install
}
